package com.base.common.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.base.common.dao.UserDAO;

public class UserServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = (String)req.getParameter("method");
		if(method != null){
			if("login".equals(method)){
				this.login(req, resp);
			}else if("logout".equals(method)){
				this.logout(req, resp);
			}
		}else{
			System.out.println("invalid request!");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

	protected void logout(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		HttpSession session = req.getSession();
		
		String userName = (String)session.getAttribute("userName");
		
		if(userName == null){
			resp.sendRedirect("pages/admin/login.jsp");
			return;
		}
		session.removeAttribute("userName");
		resp.sendRedirect("pages/admin/login.jsp");
	}
	
	protected void login(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String userName = (String)req.getParameter("userName");
		String password = (String)req.getParameter("password");
		
		if(userName == null || password == null){
			resp.sendRedirect("pages/admin/login.jsp");
		}
		UserDAO userDao = new UserDAO();
		boolean result = false;
		result = userDao.isValid(userName, password);
		if(result){
			HttpSession session = req.getSession();
			session.setAttribute("userName", userName);
			resp.sendRedirect("pages/admin/admin.jsp");
			return;
		} else{
			resp.sendRedirect("pages/admin/login.jsp");
			return;
		}
	}


}
